package cn.abcsys.cloud.devops.web.controller;


import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import cn.abcsys.cloud.devops.web.entity.GridBean;
import cn.abcsys.cloud.devops.web.entity.PagerModel;
import cn.abcsys.cloud.devops.web.entity.Role;
import cn.abcsys.cloud.devops.web.entity.User;
import cn.abcsys.cloud.devops.web.entity.UserRoleEnvProj;
import cn.abcsys.cloud.devops.web.service.RoleService;
import cn.abcsys.cloud.devops.web.util.Result;

/**
 * 用户信息控制器
 * @author xzg
 *
 */
@RestController
@RequestMapping("/role")
public class RoleUserController {
	private static final Logger LOGGER = Logger.getLogger(RoleUserController.class);
	@Resource
	private RoleService roleService;
	/**
	 * 为用户批量增加角色
	 * @param listURE
	 * @return
	 */
	@RequestMapping(value = "/addRoleForUser", method = { RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public Result addRoleForUser(@RequestBody List<UserRoleEnvProj> userRoleEnv){
		if(null == userRoleEnv){
			return new Result(false, "请求失败！");
		}
		int i =	roleService.addUserRole(userRoleEnv);
		if(0 == i)
			return new Result(false, "为用户添加角色失败！");
		else
			return new Result(true, "为用户添加角色成功！");
	}
	
	/**
	 * 为用户增加角色
	 * @param listURE
	 * @return
	 */
	@RequestMapping(value = "/addRoleUserEnv", method = { RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public Result addRoleUser(UserRoleEnvProj ure){
		int i =	roleService.addRoleUserEnv(ure);
		if(0 == i)
			return new Result(false, "为用户添加角色失败！");
		else
			return new Result(true, "为用户添加角色成功！");
	}
	/**
	 * 新增角色
	 * @param 
	 * @return
	 */
	@RequestMapping(value = "/create", method = { RequestMethod.POST})
	@ResponseBody
	public Result addRole(HttpSession session,@RequestBody Role role){
		User loginUser = null;
		if(null != session && null != (User) session.getAttribute("user"))
				loginUser = (User) session.getAttribute("user");
		else
			return new Result(false,"会话失效请重新登录");
		Result result = new Result();
		try {
			 role.setRoleCreator(loginUser.getUserId());//保存用户的创建者
			 roleService.addRole(role);
			 result.setMessage("添加角色成功！");
			 result.setSuccess(true);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			result.setMessage("添加角色失败！");
			result.setSuccess(false);
			LOGGER.error("角色插入失败");
		}
		return result;
	}
	/**
	 * 查询角色信息
	 * @param listURE
	 * @return
	 */
	@RequestMapping(value = "/list", method = { RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public GridBean selectUnderRole(@RequestBody Map<String, Object> params){
		//List<Role> roleList = roleService.getRoleByName(role);
		if( null == params){
			LOGGER.error("请求参数为空");
			return null;
		}else{
			try{
				//JSONObject paramIn = JSONObject.parseObject(params);
				JSONObject paramIn = new JSONObject(params);
				PagerModel pagerModel = paramIn.toJavaObject(PagerModel.class);
				Role role = new Role();
				role.setRoleName(paramIn.getString("roleName"));
				return roleService.getRoleByName(role, pagerModel);
			}catch(Exception e){
				LOGGER.error("请求参数转换错误："+e.getMessage());
				return null;
			}
		}
	}
	/**
	 * 查看可修改角色
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/getUnderRoles", method = { RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public Result getUnderRoles(HttpSession session,@RequestBody UserRoleEnvProj ure){
		User loginUser = null;
		if(null != session && null != (User) session.getAttribute("user"))
				loginUser = (User) session.getAttribute("user");
		else
			return new Result(false,"会话失效请重新登录");
		
		List<Role> mySelfRole = roleService.getRoleByUserEnv(ure);
		List<Role> roles = roleService.getRolePermmitMod(loginUser);
		 Map<String, List<Role>> map = new HashMap<String, List<Role>>();
		 map.put("roles", roles);
		 map.put("myrole", mySelfRole);
		if(null == roles || 0 == roles.size())
			return new Result(false, "无结果返回！");
		else
			return new Result(true, map, "操作成功");
	}
	
	/**
	 * 修改角色信息	
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/updateUnderRoles", method = { RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public Result updateUserRoles(@RequestBody Role role){
		int re = 0;
		try {
			re = roleService.updateRoleById(role);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(0 == re)
			return new Result(false, "更新失败");
		else
			return new Result(true, "更新成功");
	}
	
	/**
	 * 删除角色
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/delete", method = { RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public Result deleteRole(@RequestBody Map<String, Integer> map){
		
		LOGGER.info("roleId:"+map.get("roleId"));
		Integer roleId = map.get("roleId");
		if(null == roleId)
			 return new Result(false, "角色删除失败");
		int re =roleService.deleteRoleById(roleId);
		if(0 == re)
			return new Result(false, "角色删除失败");
		else
			return new Result(true, "角色删除成功");
		
	}
	
	/**
	 * 用户角色环境项目关联
	 * 用户项目环境关联
	 * @param listURE
	 * @return
	 *//*
	@RequestMapping(value = "/addRoleUser", method = { RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public Result addRoleUserProject(@RequestBody Map<String,Object> roleInfo){
		String roleFlag = (String) roleInfo.get("roleFlag");
		UserRoleEnv userRoleEnv = (UserRoleEnv) roleInfo.get("ure");
		ProjectUser projectUser = (ProjectUser) roleInfo.get("pue");
		if(null == roleFlag || null == userRoleEnv)
			return new Result(false, "请确认数据");
		try {
			//1、当添加环境管理员时，增加nacha_user_role_env_proj(用户-角色-环境-项目关联)表
			roleService.addRoleUserEnv(userRoleEnv);
			//2、当为项目管理员或普通用户需要添加nacha_user_role_env_proj
			if("project".equals(roleFlag))
				
				projectUserService.addProjectUser(projectUser);
			
			return new Result(true, "为用户添加角色成功！");
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				LOGGER.error("执行增加失败："+e.getMessage());
				e.printStackTrace();
			}
			return new Result(false, "为用户添加角色失败！");
	}*/
	
	/*//清除用户关联的角色、环境、项目信息
	@RequestMapping(value="clerarUesrEnvRoleProj",method={RequestMethod.POST})
	@ResponseBody
	public Result clearUserRoleEnvProj(@RequestBody Map<String,Integer> map){
		Integer userId = map.get("userId");
		Integer envId = map.get("envId");
		if(null == userId || null == envId)
			return new Result(false, "输入数据为空请再次检查");
		try{
			roleService.deleteUserEnvRoleProj(userId, envId);
			return new Result(true, "清除成功");
		}catch (SQLException e) {
			LOGGER.error("清除用户环境项目关联操作失败"+e.getMessage());
			return new Result(true, "执行成功");
		}
	}*/
}
